#encoding: utf-8
class Backend::UserController < ApplicationController
  before_filter :check_admin_priviledge
  def index
     #list user list
     @users = Student.joins(:student_profile).page(params[:page]).per(10)
  end

  def view
    # code here
    @student = Student.find_by_id(params[:user_id])
    if @student.nil?
      flash[:alert] = t"updateprofile.error.nouser"
      redirect_to :controller => "backend/user", :action => "index"
    else
      @student_profile = @student.student_profile
    end
  end

  def edit
    @student = Student.find_by_id(params[:user_id])
    if @student.nil?
      flash[:alert] = t"updateprofile.error.nouser"
      redirect_to :controller => "backend/user", :action => "index"
    else
      @student_profile = @student.student_profile
    end

    if @student_profile.nil?
      @student_profile = StudentProfile.new()    #prevent unidentified object error
    end
    if request.post?
      if @student.nil?
        flash.now.alert = t"updateprofile.error.wrongparameters"
      else
        callback = @student.update_profile(params)
        if callback.nil? or callback.blank?
          session[:profile_updated] = true
          flash[:notice] = t"updateprofile.success.profileupdated"
          redirect_to request.fullpath
        else
          flash[:alert] = callback
        end
      end
    end
  end

  def delete
    # code here
    @student = Student.find_by_id(params[:user_id])
    if @student.nil?
      flash[:alert] = t"updateprofile.error.nouser"
    else
      #check admin
      if StudentGroupLink.check_admin(@student.id) and @student.id == 1
        flash[:alert] = t"updateprofile.error.deleteadmin"
      else
        #delete all records
        if @student.delete_all_records
          flash[:notice] = "Đã xóa thông tin người dùng"
          redirect_to :controller => "backend/user", :action => "index"
        else
          flash[:alert] = "Gặp lỗi khi xóa thông tin"
        end
      end
    end
    unless flash[:alert].nil?
      redirect_to :controller => "backend/user", :action => "index"
    end
  end
end
